'''
Created on May 4, 2016

@author: liul32
'''

import os
import argparse
from subprocess import PIPE, Popen

def which(program):
    def is_exe(fpath):
        flag = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
        return flag
    
    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program

    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path,program)
            if is_exe(exe_file):
                return exe_file
            
    return None

class AccurevCommand(object):
    '''
    AccurevCommand class generates accurev command object based on 'accurev' commands
    '''
    def __init__(self, cwd = None, **params):
        if len(params) != 0:
            self.params = params
        self.accurev_exec = which('ac')
        if cwd is None and self.params['ws_path']:
            self.cwd = self.params['ws_path']
        else:
            self.cwd = cwd
        if not self.accurev_exec:
            print "Cannot find accurev executable"
    
    def run(self, timeout=300):
        run_command = [self.accurev_exec] + self.command
        #print(run_command, self.cwd)
        process = Popen(run_command, stdout = PIPE, stderr = PIPE, cwd = self.cwd)
        out, err = process.communicate()
        errorcode = process.returncode
        if errorcode != 0:
            print "Find Error Messages: \n"+err
        return (errorcode, out, err)
    
    def ac_hist(self):
            if self.params['txn']:
                txn = self.params['txn']
                self.command = ['hist','-t',txn]
                errorcode, out, err = self.run()
                if errorcode == 0:
                    return (out, True)
            else:
                print "[Parameter Errors] Miss parameter of stream"
                return (err,False)
    
if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog = 'txn2filelist.py')
    parser.add_argument('--workspace', action = 'store', dest = 'ws_path',help = 'add workspace path based on target stream', required = True)
    parser.add_argument('--transaction', action = 'store', dest = 'txn', help = 'add transaction needs to convert into file list', required = True)
    params = parser.parse_args()
    accurev_obj = AccurevCommand(ws_path = params.ws_path, txn = params.txn) 
    output, tag = accurev_obj.ac_hist()
    file_list = []
    if tag:
        out_list = output.splitlines(True)
        file_list = [ i[5:].partition(' ')[0] for i in out_list if r'/./' in i]
    print file_list        
    
    
    
